<?php

require_once 'Zend/Registry.php';
require_once 'Zend/Application.php';

class Solvex_Application extends Zend_Application
{
	    /**
     * Constructor
     *
     * Initialize application. Potentially initializes include_paths, PHP
     * settings, and bootstrap class.
     *
     * @param  string                   $environment
     * @param  string|array|Zend_Config $options String path to configuration file, or array/Zend_Config of configuration options
     * @throws Zend_Application_Exception When invalid options are provided
     * @return void
     */
    public function __construct($environment, $options = null)
    {
		$this->validate();
		
    	$this->_environment = (string) $environment;

        require_once 'Zend/Loader/Autoloader.php';
        $this->_autoloader = Zend_Loader_Autoloader::getInstance();

        if (null !== $options) {
            if (is_string($options)) {
                $options = $this->_loadConfig($options);
            } elseif ($options instanceof Zend_Config) {
                $options = $options->toArray();
            } elseif (!is_array($options)) {
                throw new Zend_Application_Exception('Invalid options provided; must be location of config file, a config object, or an array');
            }
                        
            $options['config'] = $this->getWebAppConfigFile();

            $this->setOptions($options);
        }        
    }

    public function validate()
    {
    	if(!stristr($_SERVER['REQUEST_URI'],'install')){
	    	if(!$this->isInstalled()){
				if(!headers_sent()){
					$url = str_replace('index.php','install', $_SERVER['PHP_SELF']);
					header("Location: $url");
				}
			}
		}
    }
    
    public function getWebAppConfigFile()
    {
    	if(stristr($_SERVER['REQUEST_URI'],'install')){
    		$configFile = APPLICATION_PATH . '/configs/install.xml';
    	} else {
    		$configFile = APPLICATION_PATH . '/configs/' . $this->getHost() . '.xml';
    	}
    	return $configFile;
    }
    
	public function isInstalled()
	{
		$configFile = $this->getWebAppConfigFile();
		if(is_file($configFile) && is_readable($configFile)){
			return true;
		}
		return false;
	}
	
	public function getHost()
	{
		if(Zend_Registry::isRegistered('domain_host')){
			return Zend_Registry::get('domain_host');
		}
		
		if(isset($_SERVER['HTTP_HOST'])){
			if($_SERVER['HTTP_HOST'] === '127.0.0.1'){
				$domainHost = 'localhost';
			} else {
				$domainParts = explode('.', $_SERVER['HTTP_HOST']);
				if(count($domainParts) === 1){
					$domainHost = $domainParts[0];
				} elseif($domainParts === 2){
					$domainHost = $domainParts[0] . '_' . $domainParts[1];
				} elseif($domainParts === 3){
					$domainHost = $domainParts[1] . '_' . $domainParts[2];
				}
			}
			Zend_Registry::set('domain_host', strtolower($domainHost));
		}
		
		return Zend_Registry::get('domain_host');
	}	
}